<template>
  <!-- 修改为v-if，避免v-else没有相邻的v-if -->
  <div class="searchRes">
    <div class="products-container">
      <el-empty v-if="loading" description="Loading...">
        <el-icon class="loading">
          <Loading />
        </el-icon>
      </el-empty>
      <el-empty v-else-if="products.length === 0" description="No product data is available" />
      <el-row v-else :gutter="20">
        <el-col v-for="product in products" :key="product.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="product-card" shadow="hover">
            <div class="product-content">
              <h3>name:<span style="color: brown;"> {{ product.name }}</span></h3>
              <h3>ID:<span style="color: blue;"> {{ product.id }}</span></h3>
              <h3>cate:<span style="color: blue;"> {{ product.cateId }}</span></h3>
              <p>{{ product.description }}</p>
              <p>price: ¥{{ product.price }}</p>
              <el-button type="primary" size="large" class="add-cart" @click="showDrawer(product.id)">add to
                cart</el-button>
              <el-button type="primary" size="small" class="detail" @click="viewDetail(product.id)">View
                details</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, computed, } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import store from '@/store'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import apiClient from '@/api/api'
import { onMounted,watch } from 'vue'


const router = useRouter()
const route = useRoute()
// 获取路径参数

const searchInput = computed(() => route.params.searchInput as string)
// 产品数据
const products = ref<Array<{ id: string, description: string, price: number, cateId: string,name :string }>>([]);
// 加载状态
const loading = ref(false)
// 用户是否登录
const isLoggedIn = ref(store.getters.getLoginStatus)
// 弹出层
const drawer = ref(false)
// 选中的product id
const productId = ref('')

// 显示弹出层
const showDrawer = (id: string) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  drawer.value = true
  productId.value = id
}


// 搜索按钮点击事件
const search = async () => {
  loading.value = true;
   products.value = []; // 清空之前的数据，防止数据重复添加 
  try {
    await apiClient.get(`/productList/${searchInput.value}`)
      .then((response) => {
        if (response.data.status === 0) {
          const resData = response.data.data;
         
          // 遍历响应数据，将每个产品添加到products数组中
          resData.forEach((product: any) => {
            // 发送真实请求
            apiClient.get(`/products/${product.productId}/items`)
              .then((response) => {
                if (response.data.status === 0) {
                  const length: number = response.data.data.length
                  // 遍历响应数据，将每个产品添加到products数组中
                  for (let i = 0; i < length; i++) {
                    products.value.push({
                      id: response.data.data[i].itemId,
                      description: response.data.data[i].description,
                      price: response.data.data[i].listPrice,
                      cateId: product.category,
                      name: product.name
                    })
                  }
                } else {
                  ElMessage({
                    message: response.data.message,
                    type: 'error'
                  })
                }
              })
          });
        }
      })
  }
  catch (error) {
    ElMessage.error('搜索失败，请稍后重试');
    router.push('/home')
  } finally {
    loading.value = false;
  }
};
// 查看详情
const viewDetail = (productId: string) => {
  // router.push('detail' + productId)
  router.push(`../detail/${productId}`)
}
onMounted(() => {
  search()
})
watch(searchInput, () => {
  search();
});
</script>
<style scoped>
.searchRes {

  width: 100%;
}

.products-container {
  margin-top: 20px;
}

.product-card {
  margin-bottom: 20px;
  transition: transform 0.3s ease;
  height: 100%;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-content {
  text-align: center;
  padding: 15px;
}

.product-content h3 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin-bottom: 12px;
}

.product-content p {
  font-size: 1rem;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
}

.product-content p:last-of-type {
  font-size: 1.1rem;
  color: #e6a23c;
  font-weight: 600;
  margin-bottom: 15px;
}

.product-image {
  width: 100px;
  height: auto;
  margin-bottom: 10px;
}

.loading {
  font-size: 20px;
  animation: rotating 2s linear infinite;
}

.add-cart {
  margin-top: 10px;
  margin-bottom: 10px;
  color: white;
  background-color: #0c8745;
  transition: all 0.3s ease;
  border-radius: 5px;
  padding: 8px 16px;
  font-size: 16px;
}

.add-cart:hover {
  transform: scale(1.05);
  background-color: #0da553;
  box-shadow: 0 2px 12px rgba(12, 135, 69, 0.2);
}

.add-cart:active {
  transform: scale(0.95);
  background-color: #0a7339;
}

.detail {
  margin-top: 10px;
  margin-bottom: 10px;
  color: rgb(18, 144, 227);
  border: none;
  background-color: transparent;
  text-align: center;
  text-decoration: underline;
  font-family: Arial, sans-serif;
  transition: all 0.3s ease;
  margin-right: 10px;
}

.detail:hover {
  color: rgb(12, 110, 175);
  transform: translateY(-2px);
}

.detail:active {
  transform: translateY(0);
  color: rgb(8, 82, 131);
}
</style>